(function($) {

	KOR.anchoredTabset = function(selector, parameters) {
		return KOR.AnchoredTabset.getInstanceOf(selector, parameters);
	};

	KOR.AnchoredTabset = KOR.createClass(KOR.UI, {

		NAME: 'tabset',

		activeLabelClass: "kor-anchored-tabset-label-active",
		activeContentClass: "kor-anchored-tabset-content-active",
		labelSelector: ".kor-anchored-tabset-label",
		contentSelector: ".kor-anchored-tabset-content",
		autoSizeToContent: true,

		/*
		 * @public
		 * @returns {void}
		 * @param {jQuery} label
		 * @param {jQuery} node
		 * @param {Event} ev
		 */
		show: function(label, node, ev){
			label.addClass(this.activeLabelClass);
			node.addClass(this.activeContentClass);
			node.fadeIn(300);
		},

		/**
		 * @public
		 * @returns {void}
		 * @param {jQuery} label
		 * @param {jQuery} node
		 * @param {Event} ev
		 */
		hide: function(label, node, ev){
			label.removeClass(this.activeLabelClass);
			node.removeClass(this.activeContentClass);
			node.fadeOut(300);
		},

		onDomLoad: function(ev){
			var node = $(ev.target);
			var activeLabel = node.children('.'+this.activeLabelClass);
			activeLabel.trigger(this.NAME+':show', this);
		},

		registerEvents: function() {
			this._super();
			$(document).delegate(this.selector + " " + this.labelSelector, "click", $.proxy(this, "clickHandler"));
			$(document).delegate(this.selector + " " + this.labelSelector, this.NAME+':show', $.proxy(this, 'showHandler'));
			if(this.autoSizeToContent){
				$(document).delegate(this.selector, this.NAME+':show', $.proxy(this, 'resizeHandler'));
			}
		},

		clickHandler: function(ev){
			var node = $(ev.currentTarget);
			if (node.hasClass(this.activeLabelClass)) return
			node.trigger(this.NAME+':show', this);
			return false;
		},

		resizeHandler: function(ev){
			var obj = this;
			var node = $(ev.currentTarget);
			node.trigger(obj.NAME+':show', obj);
			if(ev.target.tagName.toLowerCase() != 'a'){
				return false;
			}
		},

		showHandler: function(ev, data) {
			var target = $(ev.currentTarget);
			var link = target.children('a.kor-collection-link');
			var parent = this.getCurrentDom(target);
			var activeLabel = parent.find('.'+this.activeLabelClass);
			var activeContent = parent.find('.'+this.activeContentClass);
			this.hide(activeLabel, activeContent);
			var content = $("[id=\""+link.attr('href').replace('#','')+"\"]");
			this.show(target, content, ev);
		}

	});
})(jQuery);
